import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.text.DateFormat;
import java.text.SimpleDateFormat;



public class MulticastDB {
	
	private String filename = null;
	private String dbDelimeter = ",";
	private String recordDelimeter = " ";
	
	//methods:
	//constructors (default, filename)
	//clearDB
	//createRecord
	//deleteRecord
	//recordExists?
	//modifyRecord
	
	public MulticastDB()
	{
		this.filename = "db.csv";
	}
	
	public MulticastDB(String filename)
	{
		this.filename = filename;
	}
	
	public boolean clearDB()
	{
		FileOutputStream eraser;
		//try block
		try {
			eraser = new FileOutputStream(filename);
			eraser.write((new String()).getBytes());
			eraser.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return false;
		}		
		
		return true;
	}
	
//	public boolean createRecord(ServerQuery query)
//	{
//		try{
//		    // Create file 
//		    FileWriter fstream = new FileWriter(filename, true);
//		        BufferedWriter out = new BufferedWriter(fstream);
//		    out.write(query.getRecord());
//		    out.newLine();
//		    //Close the output stream
//		    out.close();
//		    }catch (Exception e){//Catch exception if any
//		    	return false;
//		    }
//		    
//		return true;
//	}
	
	public boolean createRecord(String record, int startIndex)
	{
		try{
		    // Create file 
		    FileWriter fstream = new FileWriter(filename, true);
		        BufferedWriter out = new BufferedWriter(fstream);
		    out.write(Helpers.arrayToDelimitedList(Helpers.extractFields(record, recordDelimeter, startIndex), dbDelimeter));
		    out.newLine();
		    //Close the output stream
		    out.close();
		    }catch (Exception e){//Catch exception if any
		    	return false;
		    }
		    
		return true;
	}
	
	public boolean createRecord(String record)
	{
		return createRecord(record, 0);
	}
	
	public boolean deleteKeywordRecords(String keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename);
    	}
    	catch (FileNotFoundException e) {
    		return false;
    	}
		BufferedReader in = new BufferedReader (inFile); 
		
		List<String> keepList = new LinkedList<String>();
		keepList = new ArrayList<String>();
		List<String> deleteList = new LinkedList<String>();
		deleteList = new ArrayList<String>();

		
		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 2 && fields[1].trim().equals(keyword))
				{
					deleteList.add(line);
				}
				else
				{
					keepList.add(line);
				}
			}
		} catch (IOException e1) {
			return false;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(deleteList.size() <= 0)
			return false; //did not find record to delete
		else
		{
			try{
			    // Create file 
			    FileWriter fstream = new FileWriter(filename);
			        BufferedWriter out = new BufferedWriter(fstream);
			    
				for (String line : keepList)
				{
					out.write(line);
					out.newLine();
				}
		
			    //Close the output stream
			    out.close();
			}catch (Exception e){//Catch exception if any
		    	return false;
		    }
		}
		return true;
	}
	
	public boolean deleteKeywordRecordsMD5(String md5keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename);
    	}
    	catch (FileNotFoundException e) {
    		return false;
    	}
		BufferedReader in = new BufferedReader (inFile); 
		
		List<String> keepList = new LinkedList<String>();
		keepList = new ArrayList<String>();
		List<String> deleteList = new LinkedList<String>();
		deleteList = new ArrayList<String>();

		
		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 1 && fields[0].trim().equals(md5keyword))
				{
					deleteList.add(line);
				}
				else
				{
					keepList.add(line);
				}
			}
		} catch (IOException e1) {
			return false;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(deleteList.size() <= 0)
			return false; //did not find record to delete
		else
		{
			try{
			    // Create file 
			    FileWriter fstream = new FileWriter(filename);
			        BufferedWriter out = new BufferedWriter(fstream);
			    
				for (String line : keepList)
				{
					out.write(line);
					out.newLine();
				}
		
			    //Close the output stream
			    out.close();
			}catch (Exception e){//Catch exception if any
		    	return false;
		    }
		}
		return true;
	}
	
	public boolean recordExists(String keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename); 
    	}
    	catch (FileNotFoundException e) {
    		return false;
    	}
		BufferedReader in = new BufferedReader (inFile);
		
		List<String> matchList = new LinkedList<String>();
		matchList = new ArrayList<String>();

		
		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 2 && fields[1].trim().equals(keyword))
				{
					matchList.add(line);
				}
			}
		} catch (IOException e) {
			return false;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(matchList.size() <= 0)
			return false; //did not find record to delete
		return true;
	}
	
	public boolean recordExistsMD5(String md5keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename); 
    	}
    	catch (FileNotFoundException e) {
    		return false;
    	}
		BufferedReader in = new BufferedReader (inFile);
		
		List<String> matchList = new LinkedList<String>();
		matchList = new ArrayList<String>();

		
		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 1 && fields[0].trim().equals(md5keyword))
				{
					matchList.add(line);
				}
			}
		} catch (IOException e) {
			return false;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(matchList.size() <= 0)
			return false; //did not find record to delete
		return true;
	}
	
//	public boolean modifyRecord(String keyword, ServerQuery newQuery)
//	{
//		boolean success = true;
//		if(recordExists(keyword))
//		{
//			success &= deleteKeywordRecords(keyword);
//			success &= createRecord(newQuery);
//		}
//		else
//			return false;
//
//		return success;
//	}
	
	public boolean modifyRecord(String keyword, String record)
	{
		boolean success = true;
		if(recordExists(keyword))
		{
			success &= deleteKeywordRecords(keyword);
			success &= createRecord(record, 0);
		}
		else
			return false;

		return success;
	}
	
	public boolean modifyRecordMD5(String md5keyword, String record)
	{
		boolean success = true;
		if(recordExistsMD5(md5keyword))
		{
			success &= deleteKeywordRecordsMD5(md5keyword);
			success &= createRecord(record, 0);
		}
		else
			return false;

		return success;
	}
	
	public String[] getRecord(String keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename); 
    	}
    	catch (FileNotFoundException e) {
    		return null;
    	}
		BufferedReader in = new BufferedReader (inFile);
		
		List<String> matchList = new LinkedList<String>();
		matchList = new ArrayList<String>();

		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 2 && fields[1].trim().equals(keyword))
				{
					matchList.add(line);
				}
			}
		} catch (IOException e) {
			return null;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(matchList.size() <= 0)
			return null; //did not find record to delete
		return matchList.get(0).split(dbDelimeter);
	}
	
	public String[] getRecordMD5(String md5keyword)
	{
		FileReader inFile = null;
    	try{
    		inFile = new FileReader (filename); 
    	}
    	catch (FileNotFoundException e) {
    		return null;
    	}
		BufferedReader in = new BufferedReader (inFile);
		
		List<String> matchList = new LinkedList<String>();
		matchList = new ArrayList<String>();

		try {
			while(in.ready())
			{
				String line = in.readLine();
				String[] fields = line.split(dbDelimeter);
				if(fields.length >= 1 && fields[0].trim().equals(md5keyword))
				{
					matchList.add(line);
				}
			}
		} catch (IOException e) {
			return null;
		}
		try {
			in.close();
			inFile.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(matchList.size() <= 0)
			return null; //did not find record to delete
		return matchList.get(0).split(dbDelimeter);
	}
}
